package com.peycard.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.peycard.service.LoginService;
import com.peycard.util.Utils;

/**
 * Servlet implementation class CambiarPassword
 */
public class CambiarPassword extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CambiarPassword() {
		super();
	}

	protected void changePassword(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		String username = (String) request.getParameter("username");
		String newPassword = (String) request.getParameter("newpassword");
		String repeatPassword = (String) request.getParameter("repeatpassword");
		try {
			if (newPassword.equals(repeatPassword)) {
				List<Object> list = new ArrayList<Object>();
				list.add(username);
				list.add(newPassword);
				String data = Utils.buildStringData(list);
				LoginService loginService = new LoginService();
				boolean boolResponse = loginService.changePassword(data);

				if (boolResponse) {
					RequestDispatcher requestDispatchet = request
							.getRequestDispatcher("/index.jsp");
					requestDispatchet.forward(request, response);
				} else {
					String message = loginService.getMessage();
					request.setAttribute("message", message);
					RequestDispatcher requestDispatchet = request
							.getRequestDispatcher("/reestablece.jsp");
					requestDispatchet.forward(request, response);
				}
			} else {
				String message = "Las contraseñas no coinciden";
				request.setAttribute("message", message);
				RequestDispatcher requestDispatchet = request
						.getRequestDispatcher("/reestablece.jsp");
				requestDispatchet.forward(request, response);
			}
		} catch (ParseException e) {
			String exceptionMsg = "Ocurrió un error al parsear la petición";
			request.setAttribute("message", exceptionMsg);
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		changePassword(request, response);
	}

}
